import router from '@/router/index.js';
import { message } from 'ant-design-vue';

export const toFormData = R.compose(
  R.converge(
    R.reduce((formData, pair) => ( formData.append(...pair), formData )),
    [R.constructN(0, FormData), Object.entries],
  ),
  R.map(R.when( R.isNil, R.always('') ))
)

/** @returns {RequestInit} */
const RequInitDef = () => ({
  headers: {
    accesstoken: localStorage.getItem('accessToken') || '',
  },
});

export const SignInInfoInvalidCondPair = () => [
  R.compose( R.equals(-99), Number, R.prop('code') ),
  () => {
    // message.error('请重新登录');
    // router.replace('/sign-in');
  }
];

/** @returns {Net.ResponseOptions} */
const RespOptsDef = () => ({
  pred: R.compose( R.equals(200), Number, R.prop('code') ),
  fail: R.identity,
});

/** @param {Net.ResponseOptions} opts */
export const useResp = (opts = {}) => value => {
  const respOpts = R.mergeDeepRight(RespOptsDef(), opts);
  return R.ifElse(respOpts.pred, respOpts.succ, respOpts.fail)(value);
};

/**
 * 发请求
 * @param {RequestInfo | URL} input
 * @param {RequestInit} init
 * @returns {Promise<any>}
 */
export function REQU(input, init = {}, opts = { showError: true }) {
  return fetch(input, R.mergeDeepRight(RequInitDef(), init))
  .then(response => response.json())
  .catch(
    R.pipe(
      R.prop('message'),
      R.when(
        () => opts.showError,
        R.pipe( R.tap(console.log), R.tap(content => message.error({ content, maxCount: 1 }))
      ))
    )
  );
}

export const getTaskInfo = id => REQU(`/api/task/info?${ new URLSearchParams({ id }) }`);

export function getUserInfo(id) {
  return REQU(`/api/user/info?${ new URLSearchParams({ id }) }`)
  .then(useResp({
    succ: R.prop('data'),
    fail: () => null
  }))
}

export const getAssignedFileList = packageId => REQU(`/api/task/assignedFileList?${ new URLSearchParams({ packageId }) }`);
